//
//  NewShowCompanyViewController.m
//  QXShowing
//
//  Created by 王道道 on 2018/7/21.
//  Copyright © 2018年 doll_dream. All rights reserved.
//

#define kCycleViewWidth       App_Frame_Width-15*2
#define kCycleViewHeight      App_Frame_Width * 180/345
#define kHeadInfoHeight       130
#define kBtnWidth  (App_Frame_Width-35-25-25)/2


#import "NewShowCompanyViewController.h"

#import "BannerViewCell.h"
#import "BannerCycleView.h"

#import "UIButton+ClickAction.h"
#import "CompanyInfoModel.h"

#import "ProductListTableViewCell.h"
#import "CompanyHeaderView.h"

#import "CompanyProductModel.h"

#import "IMChatViewController.h"

static NSString *const listVC1 = @"listVC1";
static NSString *const listVC2 = @"listVC2";
static NSString * const reusableProductViewIdentifier = @"BannerViewCell";
static NSString *const listCell = @"listCell";

@interface NewShowCompanyViewController ()<BannerCycleViewDelegate,BannerCycleViewDataSource,UITableViewDelegate,UITableViewDataSource,TabelViewRefreshDelegate>

@property (nonatomic, strong) BannerCycleView *cycleView;
@property (nonatomic, strong) CompanyHeaderView *companyHeader;
@property (nonatomic, strong) UIButton *chatBtn;

@property (nonatomic, strong) NSArray *cycleArray;
@property (nonatomic, strong) CompanyInfoModel *dataModel;

@property (nonatomic, strong) RefreshTableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation NewShowCompanyViewController

- (BannerCycleView *)cycleView {
    if (_cycleView == nil) {
        _cycleView = [[BannerCycleView alloc] initWithFrame:CGRectMake(15,10, kCycleViewWidth, kCycleViewHeight)];
        _cycleView.dataSource = self;
        _cycleView.delegate = self;
        _cycleView.showPageControl = YES;
        _cycleView.pageControlPosition = BannerCyclePageControlPositionCenter;
        _cycleView.timeInterval = 3.f;
        _cycleView.itemSpace = 30;
        [_cycleView registerClass:[BannerViewCell class] forCellWithReuseIdentifier:reusableProductViewIdentifier];
        [self.view addSubview:_cycleView];
    }
    return _cycleView;
}

#pragma mark - Lazy
//- (RefreshTableView *)tableView {
//    if (_tableView == nil) {
//        _tableView = [[RefreshTableView alloc]initWithFrame:CGRectMake(0, kCycleViewHeight+20, App_Frame_Width, App_Frame_Height-kCycleViewHeight-10-45-10-20) style:UITableViewStyleGrouped];
//        _tableView.delegate = self;
//        _tableView.dataSource = self;
//        _tableView.isRefresh = YES;
//        _tableView.refreshDelegate = self;
//        _tableView.tableHeaderView = [[UIView alloc]init];
//        _tableView.tableFooterView = [[UIView alloc]init];
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
//        _tableView.scrollsToTop = NO;
//
//        _tableView.backgroundColor = Bg_Color_FEFDFD;
//        [self.view addSubview:_tableView];
//    }
//    return _tableView;
//}

- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (CompanyHeaderView *)companyHeader {
    if (_companyHeader == nil) {
        _companyHeader = [[CompanyHeaderView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, 200)];
    }
    return _companyHeader;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"企业名录";
    [self initNavBarBackBtn];

    [self setUpUI];
    
    [self requestPostBH_Exhibition_getPicByBoothId];
    [self requestPostBH_Exhibition_getCompanyInfoByBoothId];
    
    [self requestPostBH_Exhibition_addUserFootPrint];
}

- (void)setUpUI {
    self.tableView = [[RefreshTableView alloc]initWithFrame:CGRectMake(0, kCycleViewHeight+20, App_Frame_Width, App_Frame_Height-kCycleViewHeight-10-45-10-20) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.isRefresh = YES;
    self.tableView.refreshDelegate = self;
    self.tableView.tableHeaderView = [[UIView alloc]init];
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.scrollsToTop = NO;
    self.tableView.tableHeaderView = self.companyHeader;
    self.tableView.backgroundColor = Bg_Color_FEFDFD;
    [self.view addSubview:_tableView];
    
    self.chatBtn = [[UIButton alloc] init];
    self.chatBtn.backgroundColor = Bg_Color_FFFFFF;
    [self.chatBtn setTitle:@"找他聊聊" forState:UIControlStateNormal];
    [self.chatBtn setTitleColor:Text_Color_333333 forState:UIControlStateNormal];
    [self.chatBtn setImage:[UIImage imageNamed:@"home-16"] forState:UIControlStateNormal];
    [self.chatBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 15, 0, 0)];
    [self.chatBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 10)];
    self.chatBtn.layer.masksToBounds = YES;
    self.chatBtn.layer.cornerRadius = 5;
    self.chatBtn.layer.borderColor = Bg_Color_333333.CGColor;
    self.chatBtn.layer.borderWidth = 1;
    [self.tableView addSubview:self.chatBtn];
    [self.chatBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(25);
//        make.bottom.equalTo(self.view.mas_bottom).offset(-50);
        make.bottom.equalTo(self.view.mas_bottom).offset(-10);
        make.height.offset(45);
        make.width.offset(kBtnWidth);
    }];
    
    [self.chatBtn addTarget:self action:@selector(sendMessageClick:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 按钮
- (void)sendMessageClick:(UIButton *)sender {
    BOOL ifLoginOK = [EMClient sharedClient].isLoggedIn;
    SGUserModel *model = [SGUserInfo getUserInfo];
    if (ifLoginOK) {
        [self gotoChatAction];
    } else {
//        [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:model.hx_user_name password:model.hx_password completion:^(NSDictionary *loginInfo, EMError *error) {
//            if (!error && loginInfo) {
//                NSLog(@"登录成功");
//                [self gotoChatAction];
//            }
//        } onQueue:nil];
        
        [[EMClient sharedClient] loginWithUsername:model.hx_user_name password:model.hx_password completion:^(NSString *aUsername, EMError *aError) {
            if (aError == nil) {
                [self gotoChatAction];
            } else {
                [[BHAlertUtil alertManager] showPromptInfo:@"暂无聊天账号，重新登录试试～"];
            }
        }];
    }
}

- (void)gotoChatAction {
    if (![BHSettingUtil dataAndStringIsNull:self.dataModel.hx_user_name]) {
        IMChatViewController *chatVC = [[IMChatViewController alloc] initWithConversationChatter:self.dataModel.hx_user_name conversationType:EMConversationTypeChat];
        chatVC.title = self.dataModel.company_name;
        NSDictionary *dic = @{@"easemobuserId":[BHSettingUtil dataAndStringIsNull:self.dataModel.hx_user_name]?@"":self.dataModel.hx_user_name,@"userName":[BHSettingUtil dataAndStringIsNull:self.dataModel.company_name]?@"":self.dataModel.company_name,@"userImage":@""};
        [[ContactDataObject shareInstance]insertData:dic];
        [self pushViewController:chatVC animated:YES];
    } else {
        [[BHAlertUtil alertManager] showPromptInfo:@"sorry，对方无账号"];
    }
}

#pragma mark - BannerCycleViewDelegate,BannerCycleViewDataSource
- (NSInteger)numberOfRowsInCycleView:(BannerCycleView *)cycleView {
    if (self.cycleArray.count == 0) {
        return 1;
    } else {
        return self.cycleArray.count;
    }
}

- (UICollectionViewCell *)cycleView:(BannerCycleView *)cycleView cellForItemAtRow:(NSInteger)row {
    BannerViewCell *cell = (BannerViewCell *)[cycleView dequeueReusableCellWithReuseIdentifier:reusableProductViewIdentifier forRow:row];
    cell.image.contentMode = UIViewContentModeScaleAspectFill;
    if (self.cycleArray.count == 0) {
        cell.image.image = [UIImage imageNamed:@"home-a-10"];
    }else {
        //        RoastingModel *model = self.homePageModel.SlideModel[row];
        NSString *picStr = self.cycleArray[row];
        if (![BHSettingUtil dataAndStringIsNull:picStr]) {
            [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", BH_PicPreString, picStr]] placeholderImage:[UIImage imageNamed:@"home-a-10"]];
        }
    }
    return cell;
}

- (CGSize)cycleView:(BannerCycleView *)cycleView sizeForItemAtRow:(NSInteger)row {
    return CGSizeMake(kCycleViewWidth, kCycleViewHeight);
}

- (void)cycleView:(BannerCycleView *)cycleView didSelectItemAtRow:(NSInteger)row {
    //    [BHPushViewObject pushSuperview:self success:nil params:self.homePageModel.SlideModel[row]];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
//    self.tableView.frame = CGRectMake(0, 0, App_Frame_Width, CGRectGetHeight(self.view.bounds));
    self.tableView.frame = CGRectMake(0, kCycleViewHeight+20, App_Frame_Width, App_Frame_Height-kCycleViewHeight-10-45-10-20);
    CGFloat height = [BHSettingUtil heightForText:self.dataModel.Description font:BHFont_Size_12 maxWidth:App_Frame_Width-30 withTextLineSpace:2] + 200;

    self.companyHeader.frame = CGRectMake(0, 0, App_Frame_Width, height);
}

#pragma mark - TabelViewRefreshDelegate
- (void)tableView:(UITableView *)tableView Refresh:(BOOL)refresh PageCount:(NSInteger)pageCount {
    [self requestPostBH_Exhibition_getProductByCompanyId:refresh PageCount:pageCount];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
    //    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ProductListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:listCell];
    if (cell == nil) {
        cell = [[ProductListTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:listCell];
    }
    
    cell.editBtn.hidden = YES;
    cell.deleteBtn.hidden = YES;
    
    cell.model = self.dataArray[indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 122.0;
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    return self.companyHeader;
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return self.companyHeader.frame.size.height;
//}

- (void)_loadData:(id)response Refresh:(BOOL)refresh {
    if (refresh) [self.dataArray removeAllObjects];
    NSArray *arr = [NSArray yy_modelArrayWithClass:[CompanyProductModel class] json:response];
    [self.dataArray addObjectsFromArray:arr];
    if (arr.count < 10) {
        [self.tableView endRefreshingWithNoMoreData];
    }
    [self.tableView reloadData];
}

//根据企业ID获取产品列表
- (void)requestPostBH_Exhibition_getProductByCompanyId:(BOOL)refresh PageCount:(NSInteger)pageCount {
    if (![BHSettingUtil dataAndStringIsNull:self.dataModel.company_id]) {
        self.dataArray.count != 0 ?: [[BHAlertUtil alertManager]showLoadingView:self.view];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:self.dataModel.company_id forKey:@"company_id"];
        [params setObject:[NSString stringWithFormat:@"%ld",(long)pageCount] forKey:@"page"];
        [params setObject:@"10" forKey:@"pagesize"];
        
        [PPHTTPRequest requestPostBH_Exhibition_getProductByCompanyId:^(id response, BOOL success) {
            if (self.dataArray.count == 0 && [response isKindOfClass:[NSString class]]) {
                //            self.collectionView.placeholderShow(YES).prompt_title((NSString *)response).isButtonHidden(YES);
            }else self.tableView.placeholderShow(NO);
            if (success && ![response isKindOfClass:[NSString class]]) {
                [self _loadData:response Refresh:refresh];
            }
            if (success && refresh == YES) {
                [self _loadData:response Refresh:refresh];
            }
            [[BHAlertUtil alertManager]hiddenLoading];
        } params:params];
    }
}

#pragma mark - 接口
- (void)_loadData:(id)result {
    self.cycleArray = (NSArray *)result;
    [self.cycleView reloadData];
}

- (void)requestPostBH_Exhibition_getPicByBoothId {
    [[BHAlertUtil alertManager]showLoadingView:self.view];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.booth_id forKey:@"booth_id"];
    
    [PPHTTPRequest requestPostBH_Exhibition_getPicByBoothId:^(id response, BOOL success) {
        if (success) {
            if ([response isKindOfClass:[NSArray class]]) {
                [self _loadData:response];
            }
        }
        else {
            //            @WeakObj(self);
            //            [self.cycleView.placeholderShow(YES) actionWithBlock:^{
            //                [selfWeak requestPostBH_Exhibition_getPicByBoothId];
            //            }];
        }
        [[BHAlertUtil alertManager]hiddenLoading];
    } params:params];
}

#pragma mark - 接口
- (void)_loadInfoData:(id)result {
    self.dataModel = [CompanyInfoModel yy_modelWithJSON:result];

    self.companyHeader.model = self.dataModel;

    if (![BHSettingUtil dataAndStringIsNull:self.dataModel.company_id]) {
        [self.tableView headerRefresh];
    }
}

//根据展位ID获取企业详细信息
- (void)requestPostBH_Exhibition_getCompanyInfoByBoothId {
    [[BHAlertUtil alertManager]showLoadingView:self.view];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.booth_id forKey:@"booth_id"];
    
    [PPHTTPRequest requestPostBH_Exhibition_getCompanyInfoByBoothId:^(id response, BOOL success) {
        if (success) {
            [self _loadInfoData:response];
        }
        else {
        }
        [[BHAlertUtil alertManager]hiddenLoading];
    } params:params];
}

//添加访问足迹
- (void)requestPostBH_Exhibition_addUserFootPrint {
    SGUserModel *userModel = [SGUserInfo getUserInfo];
    if (![BHSettingUtil dataAndStringIsNull:userModel.Id]) {
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:self.booth_id forKey:@"booth_id"];
        [params setObject:userModel.Id forKey:@"uid"];
        
        [PPHTTPRequest requestPostBH_Exhibition_addUserFootPrint:^(id response, BOOL success) {
            if (success) {
                
            }
            else {
            }
            [[BHAlertUtil alertManager]hiddenLoading];
        } params:params];
    }
}

@end
